<template>
  <div ref="chartRef" class="data-chart" :style="{ width, height }" />
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';

interface Props {
  /** 图表配置 */
  option: EChartsOption;
  /** 宽度 */
  width?: string;
  /** 高度 */
  height?: string;
  /** 主题 */
  theme?: string;
}

const props = withDefaults(defineProps<Props>(), {
  width: '100%',
  height: '400px',
  theme: 'default'
});

const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

/** 初始化图表 */
const initChart = () => {
  if (!chartRef.value) return;
  
  chartInstance = echarts.init(chartRef.value, props.theme);
  chartInstance.setOption(props.option);
};

/** 更新图表 */
const updateChart = () => {
  if (!chartInstance) return;
  chartInstance.setOption(props.option, true);
};

/** 调整图表大小 */
const resizeChart = () => {
  chartInstance?.resize();
};

/** 销毁图表 */
const disposeChart = () => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
};

// 监听配置变化
watch(() => props.option, updateChart, { deep: true });

// 监听窗口大小变化
onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  disposeChart();
});

defineExpose({
  chartInstance,
  updateChart,
  resizeChart
});
</script>

<style scoped>
.data-chart {
  min-height: 200px;
}
</style>
